#!/bin/bash

source /etc/profile
#tomcat path（服务所在目录）
tomcat_home=/opt/gateway

#tomcat start（启动服务脚本）
start_tomcat=$tomcat_home/server.sh

#tomcat PID
tomcatID=$(ps -ef|grep -w tomcat|grep -v 'grep'|awk '{print $2}')

#monitor URL 本机的访问URL（端口号要针对修改）
WebURL=http://localhost:8080/

#输出日志
TomcatMonitorLog=/tmp/TomcatMonitor.log

Monitor()
{
echo "begin monitor tomcat...[$(date +'%F %H:%M:%S')]"

if [ $tomcatID ];then
    #check URL status 
    echo "tomcatID: $tomcatID, go to check URL..."
    tomcatServiceCode=$(curl -s -o /dev/null -m 10 --connect-timeout 10 $WebURL -w %{http_code})
    if [ $tomcatServiceCode -eq 200 ];then
        echo "URLCode: $tomcatServiceCode, tomcat is fine."
    else
	    echo "tomcat is bad...URLCode: $tomcatServiceCode, error.log was print to $GetUrlInfo"
	    echo "restart tomcat..."
	    kill -9 $tomcatID
	    sleep 3
	    cd $tomcat_home
	    sleep 1
	    nohup ${start_tomcat} > $tomcat_home/nohup.out 2>&1 &
    fi
else
    echo "tomcat PID is not exists!restart tomcat..."
    cd $tomcat_home
    sleep 1
    nohup ${start_tomcat} > $tomcat_home/nohup.out 2>&1 &
fi
echo "____------_____-----_____"
}
Monitor>>$TomcatMonitorLog